import {defineStore} from "pinia";
import {loginAPI, logoutApi, registerAPI, updateInfoApi} from "@/apis/userApi.js";
import {ref} from 'vue'

export const useUserStore = defineStore("visUserStore", () => {

    const userInfo = ref({})


    const clearUserInfo = () => {  //清除用户信息
        userInfo.value = {}
    }


    const userLogin = async (account, password) => {
        const res = await loginAPI(account, password)
        console.log("登录返回结果", res)

        userInfo.value = res.data.data
        console.log(userInfo.value)
        return res
    }

    const userRegister = async (account, password, checkPassword) => {
        console.log(account, password, checkPassword)
        const res = await registerAPI(account, password, checkPassword)
        console.log("注册返回结果", res.data)
        userInfo.value = res.data.data
        console.log(userInfo.value)
        return res
    }


    const userLogout = async () => {
        const res = await logoutApi()
        console.log("登出返回结果", res)
        clearUserInfo()
        return res
    }


    const updateUserInfo = async (user) => {
        const res = await updateInfoApi(user)
        console.log("更新信息返回结果", res)
        return res
    }


    // 3. 以对象的格式把state和action return
    return {
        userInfo,
        userLogout,
        userLogin,
        userRegister,
        clearUserInfo,
        updateUserInfo
    }


}, {
    persist: true
})